package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConstantProperties minioConstantProperties;
    @Autowired
    private VodService vodService;
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //校验图片文件是否符合要求
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null){
                throw new GuiguException(500,"上传图片格式不正确");
            }
            //校验文件尺寸 最大900*900
            if(bufferedImage.getWidth() > 900 || bufferedImage.getHeight() > 900){
                throw new GuiguException(500,"上传图片尺寸过大");
            }

            //调用腾讯云校验文件是否合法
            String suggestion = vodService.scanImage(file);
            if ("block".equals(suggestion)||"review".equals(suggestion)){
                throw new GuiguException(500,"图片内容违规");
            }

            //生成全局唯一文件名称 以日期作为文件夹+随机数+后缀
            String folderName = DateUtil.today();
            String fileName = IdUtil.randomUUID();
            String fileType = FileNameUtil.extName(file.getOriginalFilename());
            String objectName = "/" + folderName + "/" + fileName + "." + fileType;
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            //返回文件在线地址
            return minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("上传文件失败",e);
            throw new GuiguException(500,"上传文件失败");
        }

    }
}
